package model

import (
	"gitee.com/lllgo/gopkg/csv"
	"gitee.com/lllgo/opsctl/pkg/conf"
	"strings"
	"time"
)

// 执行命令日志
type Log struct {
	Id int
	//创建时间字符串
	CreatedAt string
	// 执行的命令
	Cmd string
	// 执行结果
	Err string
}

func GetLog(args ...string) (logs []Log) {
	rs := logTable.GetRecords(func(r csv.Record, m csv.Meta) bool {
		if len(args) == 0 {
			return true
		}

		tmp := r.(Log)
		tmpMatchText := strings.Join([]string{tmp.Err, tmp.Cmd}, "\t")
		for _, t := range args {
			if t != "" {
				if strings.Contains(tmpMatchText, t) {
					return true
				}
			}
		}
		return false
	})

	for _, t := range rs {
		logs = append(logs, t.(Log))
	}

	return
}

func InsertCmd(args []string, result string) error {
	cmd := conf.AppName + " " + strings.Join(args, " ")
	return logTable.Insert(Log{CreatedAt: time.Now().Format(time.RFC3339), Cmd: cmd, Err: result})
}
